package cn.tedu.imop.ws.socket;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Level;
import java.util.logging.Logger;

@ServerEndpoint(value = "/socket/{userid}")
@Component
public class WebSocketServer {
    private static final Logger logger = Logger.getLogger(WebSocketServer.class.getName());
    // concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet =
            new CopyOnWriteArraySet<>();
    public WebSocketServer(){
        System.out.println("WebSocketServer()");
    }

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();

    // 用户唯一标识符
    private String userid;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userid") String userid, Session session) {
        //存储会话(session代表会话对象，我们要基于此对象实现客户端与服务端的会话)
        sessions.put(userid, session);
        this.userid = userid;
        System.out.println("userid="+userid);
        webSocketSet.add(this);// 加入set中
        try {
          sendMessage("连接成功");
          sendMessageToUser(userid+":连接成功", userid);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to send initial message", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // 从set中删除
        sessions.remove(userid);    // 移除会话
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        logger.log(Level.INFO, "收到来自客户端窗口的信息: " + message);
        broadcastMessage(message);
    }

    /**
     * 发生异常处理方法
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.log(Level.SEVERE, "WebSocket error", error);
    }

    /**
     * 群发消息
     *
     * @param message 消息内容
     * @throws IOException
     */
    public void broadcastMessage(String message) {
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed to send message to user: " + item.userid, e);
            }
        }
    }

    /**
     * 给指定用户发送消息
     *
     * @param message 消息内容
     * @param userid  用户ID
     * @throws IOException
     */
    public void sendMessageToUser(String message, String userid) throws IOException {
        Session session = sessions.get(userid);
        if (session != null && session.isOpen()) {
            //session.getBasicRemote().sendText(message);
            session.getAsyncRemote().sendText(message);
        } else {
            logger.log(Level.WARNING, "Session not found or not open for user: " + userid);
        }
    }

    /**
     * 发送消息给所有用户
     * @param message 消息内容
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        for (Map.Entry<String, Session> entry : sessions.entrySet()) {
            Session session = entry.getValue();
            if (session.isOpen()) {
                //session.getBasicRemote().sendText(message);
                session.getAsyncRemote().sendText(message);
            }
        }
    }

    /**
     * 群发自定义消息
     * @param message 消息内容
     * @throws IOException
     */
    public static void sendInfo(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed to send message to user: " + item.userid, e);
            }
        }
    }
}